package com.example.demo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class MainActivity extends AppCompatActivity {
    private static final int MSG_WEB_CONTENT = 1001;
    private static final int MSG_GET_IMG = 1002;

    private Button btn_image_request;
    private Button btn_image_loader;
    private Button btn_network_iv;
    private Button btn_glide;
    private Button btn_okhttp_get;
    private Button btn_okhttp_post;
    private Button btn_okhttp_image;

    private TextView tv_show;
    private NetworkImageView networkImageView;

    private ImageView iv_show;
    private MyImageCache myImageCache;

    // 网络请求队列
    private RequestQueue requestQueue ;

    private Handler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initHandler();

        myImageCache = new MyImageCache();
        requestQueue = Volley.newRequestQueue(MainActivity.this);

        tv_show = findViewById(R.id.tv_show);

        btn_okhttp_get = findViewById(R.id.btn_okhttp_get);
        btn_okhttp_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useAsynGet();
//                useSyncGet();
            }
        });

        btn_image_request = findViewById(R.id.btn_image_request);
        btn_image_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useImageRequest();
            }
        });

        iv_show = findViewById(R.id.iv_show);

        btn_image_loader = findViewById(R.id.btn_image_loader);
        btn_image_loader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useImageLoader();
            }
        });

        btn_network_iv = findViewById(R.id.btn_network_iv);
        networkImageView = findViewById(R.id.network_iv);

        btn_network_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useNetWorkImageView();
            }
        });

        btn_glide = findViewById(R.id.btn_glide);
        btn_glide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://jsxy.gdcp.cn/UploadFile/2/2021/2/10/2021210102839377.png";
                Glide.with(MainActivity.this).load(url).into(iv_show);
            }
        });

        btn_okhttp_post = findViewById(R.id.btn_okhttp_post);
        btn_okhttp_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useOkhttpPost();
            }
        });

        btn_okhttp_image = findViewById(R.id.btn_okhttp_image);
        btn_okhttp_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useOkhttpGetImage();
            }
        });
    }

    // 使用okhttp获取并显示图片
    private void useOkhttpGetImage() {
        String url = "http://www.gdcp.edu.cn/service?token=5a5d0c3fa9a145719be5b98f7b49eb56";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("useOkhttpGetImage", e.toString());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                Log.e("useOkhttpGetImage", response.message());

                InputStream inputStream = response.body().byteStream();
                // 怎么把流转成图片
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                // 此时还在子线程
                // iv_show.setImageBitmap(bitmap);

                // 通过消息发送到主线程
                Message message = new Message();
                message.what = MSG_GET_IMG;
                message.obj = bitmap;
                myHandler.sendMessage(message);
            }
        });


    }

    // 使用post方式查询归属地
    private void useOkhttpPost() {
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
         // "?mobileCode=13800138000&userID="; 通过post参数提交

        RequestBody requestBody = new FormBody.Builder()
                .add("mobileCode", "13456789999")
                .add("userID","")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("useOkhttpPost", e.toString());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String content = response.body().string();
                Log.e("useOkhttpPost", content);

                // 发消息到主线程
                Message message = new Message();
                message.what = MSG_WEB_CONTENT;
                message.obj = content;
                myHandler.sendMessage(message);
            }
        });
    }

    // okhttp的异步get请求
    private void useAsynGet() {
        OkHttpClient okHttpClient = new OkHttpClient();
//        String url = "http://www.qq.com";
//        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=13800138000&userID=";
        String url = "http://www.gdcp.edu.cn/service?token=5a5d0c3fa9a145719be5b98f7b49eb56";
        Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("useAsynGet", e.toString());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String content = response.body().string();
                Log.e("useAsynGet",content);
                // 不能直接调用  现在还是在子线程
                // tv_show.setText(content);

                // 发消息到主线程
                Message message = new Message();
                message.what = MSG_WEB_CONTENT;
                message.obj = content;
                myHandler.sendMessage(message);
            }
        });
    }

    // 初始化Handler
    private void initHandler() {
        myHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if(msg.what == MSG_WEB_CONTENT){
                    String content = (String) msg.obj;
                    tv_show.setText(content);
                    return true;
                }

                if(msg.what == MSG_GET_IMG){
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv_show.setImageBitmap(bitmap);
                    return true;
                }
                return false;
            }
        });
    }

    // okhttp的同步get请求
    private void useSyncGet() {
        OkHttpClient okHttpClient = new OkHttpClient();
        String url = "http://www.qq.com";
        Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    okhttp3.Response response = call.execute();
                    String content = response.body().string();
                    Log.e("useSyncGet", content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



    // 使用NetWorkImageView组件加载图片
    private void useNetWorkImageView() {
        networkImageView.setDefaultImageResId(R.drawable.loading);
        networkImageView.setErrorImageResId(R.drawable.load_fail);
        String url = "http://jsxy.gdcp.cn/UploadFile/2/2021/2/10/2021210102933139.png";
        ImageLoader imageLoader = new ImageLoader(requestQueue, myImageCache);
        networkImageView.setImageUrl(url, imageLoader);
    }

    // 使用ImageLoader加载图片
    private void useImageLoader() {
        ImageLoader imageLoader = new ImageLoader(requestQueue, myImageCache);

        ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(iv_show,
                R.drawable.loading, R.drawable.load_fail);

        String imageUrl = "http://www.gdcp.edu.cn/service?token=4b5898d29b2c4ae9abd012f2dcdd73c5";

        imageLoader.get(imageUrl, imageListener);
    }

    // 使用ImageRequest获取图片
    private void useImageRequest() {
        String imgUrl = "http://www.gdcp.edu.cn/service?token=20408ddfde6e4722a8728f3342888fdf";
        ImageRequest imageRequest = new ImageRequest(imgUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                Log.e("ImageRequest", "bitmap size = " + bitmap.getByteCount());

                // 这里就是主线程 可以直接调用组件
                iv_show.setImageBitmap(bitmap);
            }
        }, 0, 0, Bitmap.Config.RGB_565,
                new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("ImageRequest", "volleyError = " + volleyError.getMessage());
            }
        });

        // 加入到请求队列
        requestQueue.add(imageRequest);
    }
}